// 认知能力评估逻辑处理文件
// 根据"T 3.2.1认知能力记录表"设计

/**
 * 计算认知能力评估结果
 * @param {Object} formData - 表单数据
 * @returns {Object} 评估结果
 */
export function calculateCognitiveAssessment(formData) {
  // 计算各维度得分
  const attentionScore = calculateAttentionScore(formData);
  const executiveScore = calculateExecutiveScore(formData);
  const orientationScore = calculateOrientationScore(formData);
  const memoryScore = calculateMemoryScore(formData);
  const calculationScore = calculateCalculationScore(formData);
  
  // 计算总分
  // 注意(5分) + 执行功能(动物名字个数，通常满分20+) + 定向(6分) + 记忆(15分) + 计算(根据题目数量)
  const totalScore = attentionScore.total + 
                     executiveScore.total + 
                     orientationScore.total + 
                     memoryScore.total + 
                     calculationScore.total;
  
  // 根据实际测试，设置合理的最高分
  // 注意5分 + 执行功能20分(假设满分) + 定向6分 + 记忆15分 + 计算10分(假设满分) = 56分
  const maxScore = 56;
  
  // 计算百分比
  const percentage = (totalScore / maxScore) * 100;
  
  // 评估认知功能水平
  const cognitiveLevel = assessCognitiveLevel(percentage);
  
  // 生成诊断结果
  const diagnosis = generateDiagnosis(cognitiveLevel, {
    attention: attentionScore,
    executive: executiveScore,
    orientation: orientationScore,
    memory: memoryScore,
    calculation: calculationScore
  });
  
  // 生成建议
  const recommendations = generateRecommendations(cognitiveLevel, {
    attention: attentionScore,
    executive: executiveScore,
    orientation: orientationScore,
    memory: memoryScore,
    calculation: calculationScore
  });
  
  return {
    totalScore: totalScore,
    maxScore: maxScore,
    percentage: percentage.toFixed(1),
    cognitiveLevel: cognitiveLevel.level,
    cognitiveLevelName: cognitiveLevel.name,
    cognitiveLevelDescription: cognitiveLevel.description,
    diagnosis: diagnosis,
    recommendations: recommendations,
    dimensions: {
      attention: attentionScore,
      executive: executiveScore,
      orientation: orientationScore,
      memory: memoryScore,
      calculation: calculationScore
    },
    summary: generateSummary(totalScore, maxScore, percentage, cognitiveLevel, diagnosis)
  };
}

/**
 * 计算注意力得分
 */
function calculateAttentionScore(formData) {
  // 检查记住的词语数量（只计算值为'remembered'的词语）
  let rememberedCount = 0;
  const words = ['attentionWord1', 'attentionWord2', 'attentionWord3', 'attentionWord4', 'attentionWord5'];
  words.forEach(wordId => {
    if (formData[wordId] === 'remembered') {
      rememberedCount++;
    }
  });
  
  // 使用输入的得分，如果没有则使用记住的词语数量
  const score = parseInt(formData.attentionScore) || rememberedCount;
  const max = 5;
  const percentage = (score / max) * 100;
  
  let level = '正常';
  if (percentage < 40) {
    level = '重度受损';
  } else if (percentage < 60) {
    level = '中度受损';
  } else if (percentage < 80) {
    level = '轻度受损';
  }
  
  return {
    rememberedWords: rememberedCount,
    score: score,
    total: score,
    max: max,
    percentage: percentage.toFixed(1),
    level: level
  };
}

/**
 * 计算执行功能得分
 */
function calculateExecutiveScore(formData) {
  const animalCount = parseInt(formData.animalNamesCount) || 0;
  
  // 执行功能通常以说出的动物名字数量计分
  // 正常水平通常在10-20个以上
  const max = 20; // 假设满分为20个
  const percentage = (animalCount / max) * 100;
  
  let level = '正常';
  if (percentage < 30) {
    level = '重度受损';
  } else if (percentage < 50) {
    level = '中度受损';
  } else if (percentage < 70) {
    level = '轻度受损';
  }
  
  return {
    animalNamesCount: animalCount,
    total: animalCount,
    max: max,
    percentage: percentage.toFixed(1),
    level: level
  };
}

/**
 * 计算定向得分
 */
function calculateOrientationScore(formData) {
  const score = parseInt(formData.orientationScore) || 0;
  const max = 6; // 年、月、日、星期几、地点、城市共6项
  const percentage = (score / max) * 100;
  
  let level = '正常';
  if (percentage < 50) {
    level = '重度受损';
  } else if (percentage < 67) {
    level = '中度受损';
  } else if (percentage < 83) {
    level = '轻度受损';
  }
  
  return {
    score: score,
    total: score,
    max: max,
    percentage: percentage.toFixed(1),
    level: level,
    details: {
      year: formData.orientationYear,
      month: formData.orientationMonth,
      day: formData.orientationDay,
      weekday: formData.orientationWeekday,
      location: formData.orientationLocation,
      city: formData.orientationCity
    }
  };
}

/**
 * 计算记忆得分
 */
function calculateMemoryScore(formData) {
  const noHintScore = parseInt(formData.memoryNoHintScore) || 0;
  const categoryHintScore = parseInt(formData.memoryCategoryHintScore) || 0;
  const multipleChoiceScore = parseInt(formData.memoryMultipleChoiceScore) || 0;
  
  const total = noHintScore + categoryHintScore + multipleChoiceScore;
  const max = 15; // 三种方式各5分，共15分
  const percentage = (total / max) * 100;
  
  let level = '正常';
  if (percentage < 40) {
    level = '重度受损';
  } else if (percentage < 60) {
    level = '中度受损';
  } else if (percentage < 80) {
    level = '轻度受损';
  }
  
  return {
    noHintScore: noHintScore,
    categoryHintScore: categoryHintScore,
    multipleChoiceScore: multipleChoiceScore,
    total: total,
    max: max,
    percentage: percentage.toFixed(1),
    level: level
  };
}

/**
 * 计算计算能力得分
 */
function calculateCalculationScore(formData) {
  const score = parseInt(formData.calculationScore) || 0;
  const max = 10; // 假设满分为10分（根据实际题目数量调整）
  const percentage = (score / max) * 100;
  
  let level = '正常';
  if (percentage < 40) {
    level = '重度受损';
  } else if (percentage < 60) {
    level = '中度受损';
  } else if (percentage < 80) {
    level = '轻度受损';
  }
  
  return {
    score: score,
    total: score,
    max: max,
    percentage: percentage.toFixed(1),
    level: level,
    details: {
      question1: formData.calculationQuestion1,
      answer1: formData.calculationAnswer1,
      question2: formData.calculationQuestion2,
      answer2: formData.calculationAnswer2,
      question3: formData.calculationQuestion3,
      answer3: formData.calculationAnswer3
    }
  };
}

/**
 * 评估认知功能水平
 */
function assessCognitiveLevel(percentage) {
  if (percentage >= 90) {
    return {
      level: 'excellent',
      name: '优秀',
      description: '认知功能优秀，各项能力均正常'
    };
  } else if (percentage >= 80) {
    return {
      level: 'good',
      name: '良好',
      description: '认知功能良好，基本正常'
    };
  } else if (percentage >= 70) {
    return {
      level: 'mild',
      name: '轻度受损',
      description: '认知功能轻度受损，需要关注'
    };
  } else if (percentage >= 50) {
    return {
      level: 'moderate',
      name: '中度受损',
      description: '认知功能中度受损，建议进一步评估'
    };
  } else if (percentage >= 30) {
    return {
      level: 'severe',
      name: '重度受损',
      description: '认知功能重度受损，需要医疗干预'
    };
  } else {
    return {
      level: 'very_severe',
      name: '极重度受损',
      description: '认知功能极重度受损，需要紧急医疗干预'
    };
  }
}

/**
 * 生成诊断结果
 */
function generateDiagnosis(cognitiveLevel, dimensions) {
  const impairedDimensions = [];
  
  if (parseFloat(dimensions.attention.percentage) < 80) {
    impairedDimensions.push('注意力');
  }
  if (parseFloat(dimensions.executive.percentage) < 70) {
    impairedDimensions.push('执行功能');
  }
  if (parseFloat(dimensions.orientation.percentage) < 83) {
    impairedDimensions.push('定向能力');
  }
  if (parseFloat(dimensions.memory.percentage) < 80) {
    impairedDimensions.push('记忆力');
  }
  if (parseFloat(dimensions.calculation.percentage) < 80) {
    impairedDimensions.push('计算能力');
  }
  
  let diagnosis = `认知功能${cognitiveLevel.name}`;
  
  if (impairedDimensions.length > 0) {
    diagnosis += `，主要受损维度：${impairedDimensions.join('、')}`;
  }
  
  return diagnosis;
}

/**
 * 生成建议措施
 */
function generateRecommendations(cognitiveLevel, dimensions) {
  const recommendations = [];
  
  // 根据总体水平给出建议
  if (cognitiveLevel.level === 'excellent' || cognitiveLevel.level === 'good') {
    recommendations.push('认知功能正常，建议继续保持健康的生活方式');
    recommendations.push('定期进行认知功能评估，监测变化趋势');
  } else if (cognitiveLevel.level === 'mild') {
    recommendations.push('认知功能轻度受损，建议进行认知训练');
    recommendations.push('保持规律作息，保证充足睡眠');
    recommendations.push('增加社交活动，保持大脑活跃');
  } else if (cognitiveLevel.level === 'moderate') {
    recommendations.push('认知功能中度受损，建议咨询专科医生');
    recommendations.push('进行详细的神经心理学评估');
    recommendations.push('考虑药物治疗和认知康复训练');
  } else {
    recommendations.push('认知功能严重受损，需要立即就医');
    recommendations.push('进行全面的神经心理学和医学评估');
    recommendations.push('制定综合治疗和康复计划');
    recommendations.push('加强日常照护和安全防护');
  }
  
  // 根据具体受损维度给出针对性建议
  if (parseFloat(dimensions.attention.percentage) < 80) {
    recommendations.push('注意力训练：减少干扰，进行专注力练习');
  }
  if (parseFloat(dimensions.executive.percentage) < 70) {
    recommendations.push('执行功能训练：进行动物命名等言语流畅性练习');
  }
  if (parseFloat(dimensions.orientation.percentage) < 83) {
    recommendations.push('定向能力训练：加强时间、地点定向练习');
  }
  if (parseFloat(dimensions.memory.percentage) < 80) {
    recommendations.push('记忆力训练：使用记忆辅助工具，进行记忆游戏训练');
  }
  if (parseFloat(dimensions.calculation.percentage) < 80) {
    recommendations.push('计算能力训练：进行简单的数学运算练习');
  }
  
  return recommendations;
}

/**
 * 生成评估摘要
 */
function generateSummary(totalScore, maxScore, percentage, cognitiveLevel, diagnosis) {
  return `认知能力评估结果：
总分：${totalScore}/${maxScore} (${percentage}%)
认知功能水平：${cognitiveLevel.name}
诊断：${diagnosis}
评估时间：${new Date().toLocaleString('zh-CN')}`;
}

/**
 * 验证认知能力评估表单数据
 * @param {Object} formData - 表单数据
 * @returns {Object} 验证结果
 */
export function validateCognitiveForm(formData) {
  const errors = [];
  const warnings = [];
  
  // 个人信息字段已改为选填，不再进行必填验证
  // 只验证如果填写了年龄，则必须在有效范围内
  if (formData.age !== null && formData.age !== undefined && formData.age !== '') {
    const age = parseInt(formData.age);
    if (isNaN(age) || age < 0 || age > 150) {
      errors.push('年龄应在0-150岁之间');
    }
  }
  
  // 评估项目验证
  const requiredQuestions = [
    'attentionScore',
    'animalNamesCount',
    'orientationYear', 'orientationMonth', 'orientationDay', 'orientationWeekday', 'orientationLocation', 'orientationCity', 'orientationScore',
    'memoryNoHintScore', 'memoryCategoryHintScore', 'memoryMultipleChoiceScore',
    'calculationScore'
  ];
  
  requiredQuestions.forEach(questionId => {
    if (formData[questionId] === undefined || formData[questionId] === null || formData[questionId] === '') {
      errors.push(`评估项目"${questionId}"为必填项`);
    }
  });
  
  return {
    isValid: errors.length === 0,
    errors,
    warnings,
    hasWarnings: warnings.length > 0
  };
}

export default {
  calculateCognitiveAssessment,
  validateCognitiveForm
};
